package chapter09

/**
  * 隐式转换 Implicit -- 让程序二次编译能够通过
  */
object Test02_Implicit {

  def main(args: Array[String]): Unit = {
    val richInt = new MyRichInt(13)
    println(richInt.myMax(15))

    //1.隐式函数
    implicit def convert(num: Int): MyRichInt = new MyRichInt(num)

    println(12.myMax(15))

    // 2.隐式类
    implicit class MyRichInt2(val self: Int) {
      // 自定义比较大小的方法
      def myMax2(n: Int): Int = if (n < self) self else n

      def myMin2(n: Int): Int = if (n < self) n else self
    }

    println(12.myMax2(16))

    // 2.隐式参数,只能有一个同类型的隐式值,且隐式值优先于默认值
    implicit val str: String = "fy"

    def sayHello(self: String = "yi") = {
      println(s"hello,$self")
    }

    def sayHi1(implicit self: String) = {
      println(s"hello,$self")
    }

    def sayHi2()(implicit self: String) = {
      println(s"hello,$self")
    }
    //简便写法
    def sayHi3() = {
      println(s"hello,"+ implicitly[String])
    }

    sayHi1
    sayHi2()
    sayHi3()

  }
}

class MyRichInt(val self: Int) {
  // 自定义比较大小的方法
  def myMax(n: Int): Int = if (n < self) self else n

  def myMin(n: Int): Int = if (n < self) n else self
}
